<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  
  
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>
    自定义注解（hibernate-validator实现） |
    
    M_W_Q</title>
  
    <link rel="shortcut icon" href="/bolg/favicon.ico">
  
  <link rel="stylesheet" href="/bolg/css/style.css">
  
    <link rel="stylesheet" href="/bolg/fancybox/jquery.fancybox.min.css">
  
  <script src="/bolg/js/pace.min.js"></script>
</head>

<body>
<main class="content">
  <section class="outer">
  

<article id="post-自定义注解" class="article article-type-post" itemscope itemprop="blogPost" data-scroll-reveal>
  
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      自定义注解（hibernate-validator实现）
    </h1>
  
  




      </header>
    

    
      <div class="article-meta">
        <a href="/bolg/2019/10/23/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3/" class="article-date">
  <time datetime="2019-10-23T12:11:20.109Z" itemprop="datePublished">2019-10-23</time>
</a>
        
      </div>
    

    
      
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
        <h3 id="自定义注解（hibernate-validator实现）"><a href="#自定义注解（hibernate-validator实现）" class="headerlink" title="自定义注解（hibernate-validator实现）"></a>自定义注解（hibernate-validator实现）</h3><hr>
<h4 id="pom添加"><a href="#pom添加" class="headerlink" title="pom添加"></a>pom添加</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    </span><br><span class="line"><span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.hibernate<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    </span><br><span class="line"><span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hibernate-validator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">version</span>&gt;</span>4.3.1.Final<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="注解编写"><a href="#注解编写" class="headerlink" title="注解编写"></a>注解编写</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*** * 功能描述: &lt;br&gt; * &lt; 字符串不为空串&gt; * * </span></span><br><span class="line"><span class="comment"><span class="doctag">@param</span> null * <span class="doctag">@return</span>: * </span></span><br><span class="line"><span class="comment"><span class="doctag">@since</span>: 1.0.0 * </span></span><br><span class="line"><span class="comment"><span class="doctag">@Author</span>:Administrator * </span></span><br><span class="line"><span class="comment"><span class="doctag">@Date</span>: 2019/8/16 14:24 */</span></span><br><span class="line"><span class="meta">@Target</span>(&#123;METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER,TYPE_USE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Constraint</span>(validatedBy =CheckStringNotBlankCaseValidator.class)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> NotBlank &#123;   </span><br><span class="line"><span class="function">String <span class="title">message</span><span class="params">()</span> <span class="keyword">default</span> "字符为空"</span>;    </span><br><span class="line">Class&lt;?&gt;[] groups() <span class="keyword">default</span> &#123;&#125;;    </span><br><span class="line">Class&lt;? extends Payload&gt;[] payload() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="具体校验实现"><a href="#具体校验实现" class="headerlink" title="具体校验实现"></a>具体校验实现</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CheckStringNotBlankCaseValidator</span> <span class="keyword">implements</span> <span class="title">ConstraintValidator</span>&lt;<span class="title">NotBlank</span>, <span class="title">String</span>&gt; </span>&#123;    </span><br><span class="line"><span class="keyword">private</span> String value;   </span><br><span class="line"><span class="meta">@Override</span>    </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initialize</span><span class="params">(NotBlank constraintAnnotation)</span> </span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Override</span>    </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isValid</span><span class="params">(String value, ConstraintValidatorContext context)</span> </span>&#123;       </span><br><span class="line"><span class="keyword">return</span> StringUtils.isNotBlank(value);   </span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="校验工具类"><a href="#校验工具类" class="headerlink" title="校验工具类"></a>校验工具类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ValidatorConfiguration</span> </span>&#123;    </span><br><span class="line"><span class="comment">/**     * 快速失败处理Validator初始化     * <span class="doctag">@return</span>     */</span>    </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Validator <span class="title">validatorFast</span><span class="params">()</span> </span>&#123;        </span><br><span class="line">ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)</span><br><span class="line">.configure()               </span><br><span class="line">.addProperty( <span class="string">"hibernate.validator.fail_fast"</span>, <span class="string">"true"</span> )               </span><br><span class="line">.buildValidatorFactory();        </span><br><span class="line">Validator validator = validatorFactory.getValidator();        </span><br><span class="line"><span class="keyword">return</span> validator;   </span><br><span class="line">&#125;   </span><br><span class="line"><span class="comment">/***     * 失败处理Validator初始化     * <span class="doctag">@return</span>     */</span>    </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Validator <span class="title">validator</span><span class="params">()</span> </span>&#123;        </span><br><span class="line">ValidatorFactory validatorFactory =Validation.byProvider(HibernateValidator.class)                </span><br><span class="line">.configure()                </span><br><span class="line">.buildValidatorFactory();       </span><br><span class="line">Validator validator = validatorFactory.getValidator();        </span><br><span class="line"><span class="keyword">return</span> validator;    </span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="注解使用工具"><a href="#注解使用工具" class="headerlink" title="注解使用工具"></a>注解使用工具</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ValidatorUtil</span> </span>&#123;    </span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Validator validator = ValidatorConfiguration.validator();    </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">ValidationResult <span class="title">validateEntity</span><span class="params">(T obj)</span> </span>&#123;        </span><br><span class="line">ValidationResult result = <span class="keyword">new</span> ValidationResult();        </span><br><span class="line">Set&lt;ConstraintViolation&lt;T&gt;&gt; set = validator.validate(obj, Default.class);       </span><br><span class="line"><span class="keyword">if</span> (CollectionUtils.isNotEmpty(set)) &#123;            </span><br><span class="line">result.setHasErrors(<span class="keyword">true</span>);            </span><br><span class="line">Map&lt;String, String&gt; errorMsg = <span class="keyword">new</span> HashMap&lt;&gt;();            </span><br><span class="line"><span class="keyword">for</span> (ConstraintViolation&lt;T&gt; cv : set) &#123;                </span><br><span class="line">errorMsg.put(cv.getPropertyPath().toString(), </span><br><span class="line">cv.getMessage());           </span><br><span class="line">&#125;           </span><br><span class="line">result.setErrorMsg(errorMsg);        </span><br><span class="line">&#125;        </span><br><span class="line"><span class="keyword">return</span> result;    </span><br><span class="line">&#125;   </span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">ValidationResult <span class="title">validateProperty</span><span class="params">(T obj, String propertyName)</span> </span>&#123;        </span><br><span class="line">ValidationResult result = <span class="keyword">new</span> ValidationResult();        </span><br><span class="line">Set&lt;ConstraintViolation&lt;T&gt;&gt; set = validator.validateProperty(obj, propertyName, Default.class);       </span><br><span class="line"><span class="keyword">if</span> (CollectionUtils.isNotEmpty(set)) &#123;            </span><br><span class="line">result.setHasErrors(<span class="keyword">true</span>);            </span><br><span class="line">Map&lt;String, String&gt; errorMsg = <span class="keyword">new</span> HashMap&lt;&gt;();            </span><br><span class="line"><span class="keyword">for</span> (ConstraintViolation&lt;T&gt; cv : set) &#123;                </span><br><span class="line">errorMsg.put(propertyName, cv.getMessage());           </span><br><span class="line">&#125;            </span><br><span class="line">result.setErrorMsg(errorMsg);       </span><br><span class="line">&#125;       </span><br><span class="line"><span class="keyword">return</span> result;   </span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://m_aleen.gitee.io/bolg/2019/10/23/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3/" data-id="ck32z8ytu000769dballra3la"
         class="article-share-link">Share</a>
      
    </footer>

  </div>

  
    
  <nav class="article-nav">
    
      <a href="/bolg/2019/10/23/java8%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/" class="article-nav-link">
        <strong class="article-nav-caption">Newer posts</strong>
        <div class="article-nav-title">
          
            java8函数式编程
          
        </div>
      </a>
    
    
      <a href="/bolg/2019/10/21/Linux%E4%B8%8B%E5%AE%89%E8%A3%85jdk%EF%BC%88Centos%E7%89%88%EF%BC%89/" class="article-nav-link">
        <strong class="article-nav-caption">Olde posts</strong>
        <div class="article-nav-title">Linux下安装jdk（Centos版）</div>
      </a>
    
  </nav>


  

  
    
  

</article>



</section>
  <footer class="footer">
  <div class="outer">
    <div class="float-right">
      <ul class="list-inline">
  
    <li><i class="fe fe-smile-alt"></i> <span id="busuanzi_value_site_uv"></span></li>
  
    <li><i class="fe fe-bookmark"></i> <span id="busuanzi_value_page_pv"></span></li>
  
</ul>
    </div>
    <ul class="list-inline">
      <li>&copy; 2019 M_W_Q</li>
      <li>Powered by <a href="http://hexo.io/" target="_blank">Hexo</a></li>
      <li>Theme  <a href="https://github.com/zhwangart/hexo-theme-ocean" target="_blank" rel="noopener">Ocean</a></li>
    </ul>
  </div>
</footer>

</main>

<aside class="sidebar sidebar-specter">
  
    <button class="navbar-toggle"></button>
<nav class="navbar">
  
    <div class="logo">
      <a href="/bolg/"><img src="/bolg/images/hexo.svg" alt="M_W_Q"></a>
    </div>
  
  <ul class="nav nav-main">
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/">Home</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/archives">Archives</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/gallery">Gallery</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/about">About</a>
      </li>
    
    <li class="nav-item">
      <a class="nav-item-link nav-item-search" title="搜索">
        <i class="fe fe-search"></i>
        Search
      </a>
    </li>
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      <div class="totop" id="totop">
  <i class="fe fe-rocket"></i>
</div>
    </li>
    <li class="nav-item">
      
        <a class="nav-item-link" target="_blank" href="/bolg/atom.xml" title="RSS Feed">
          <i class="fe fe-feed"></i>
        </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
  </aside>
  <script src="/bolg/js/jquery-2.0.3.min.js"></script>
<script src="/bolg/js/jquery.justifiedGallery.min.js"></script>
<script src="/bolg/js/lazyload.min.js"></script>
<script src="/bolg/js/busuanzi-2.3.pure.min.js"></script>

  <script src="/bolg/fancybox/jquery.fancybox.min.js"></script>



  <script src="/bolg/js/tocbot.min.js"></script>
  <script>
    // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
    tocbot.init({
      tocSelector: '.tocbot',
      contentSelector: '.article-entry',
      headingSelector: 'h1, h2, h3, h4, h5, h6',
      hasInnerContainers: true,
      scrollSmooth: true,
      positionFixedSelector: '.tocbot',
      positionFixedClass: 'is-position-fixed',
      fixedSidebarOffset: 'auto',
    });
  </script>


<script src="/bolg/js/ocean.js"></script>

</body>
</html>